from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QTextEdit
from PySide6.QtCore import Qt, QThread, Signal
import time
import subprocess

class Worker(QThread):
    finished = Signal(str)
    

    def __init__(self, bat_file):
        super().__init__()
        self.bat_file=bat_file

    def run(self):
        # 模拟耗时操作
        # bat_file = 'install.bat'
        # 使用subprocess.Popen启动批处理文件
        process = subprocess.Popen(self.bat_file, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
        # 循环读取输出
        for line in process.stdout:
            print(line, end='')  # 实时打印输出
        # 等待进程结束
        process.wait()
        result = "耗时操作完成"
        self.finished.emit(result)

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()

        self.text_edit = QTextEdit()
        self.text_edit.setReadOnly(True)
        layout.addWidget(self.text_edit)

        self.button = QPushButton("开始耗时操作")
        layout.addWidget(self.button)

        self.setLayout(layout)

        self.button.clicked.connect(self.start_operation)

    def start_operation(self):
        self.worker = Worker(bat_file=r'install.bat')
        self.worker.finished.connect(lambda:print('ok'))
        self.worker.start()

    def update_text(self, result):
        self.text_edit.append(result)

if __name__ == "__main__":
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec()
